package struct.tree.iter;

import struct.tree.node.Node;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: 柒月
 * @date: 2025/5/3 下午10:06
 * @version: 1.0
 */
public class InorderTraversal {

    public static int[] inorderRecursion(Node root) {
        List<Integer> list = new LinkedList<>();
        inorderRecursion(root, list);
        return list.stream().mapToInt(i -> i).toArray();
    }

    private static void inorderRecursion(Node root, List<Integer> list) {
        if (root == null) return;
        inorderRecursion(root.left, list);
        list.add(root.data);
        inorderRecursion(root.right, list);
    }

    public static int[] inorderIteration(Node root) {
        List<Integer> list = new LinkedList<>();
        inorderIteration(root, list);
        return list.stream().mapToInt(i -> i).toArray();
    }

    private static void inorderIteration(Node root, List<Integer> list) {
        Deque<Node> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                list.add(root.data);
                root = root.right;
            }
        }
    }
}
